const Router = require("koa-router");
const newfile = new Router();
const bodyParser = require("koa-bodyparser");
const article = require("../utils/sql");
const { getCurrentTime } = require("../utils/times");
const path = require("path");
const fs = require("fs");

newfile.use(bodyParser());

// 创建文件夹
newfile.post("/", async (ctx) => {
  const params = ctx.request.body;
  const { user_id, folder_name, created_at } = params;
  // 创建文件夹
  let data = await article.addFolder(user_id, folder_name, created_at);
  ctx.body = {
    code: 200,
    msg: "创建成功",
    data,
  };
});

// 获取文件夹列表
newfile.post("/getFolder", async (ctx) => {
  const params = ctx.request.body;
  const { id } = params;
  let data = await article.getFolder(id);
  ctx.body = {
    code: 200,
    msg: "获取成功",
    data,
  };
});

// 删除文件夹
newfile.post("/deleteFolder", async (ctx) => {
  const params = ctx.request.body;
  const { id } = params;
  let data = await article.deleteFolder(id);
  ctx.body = {
    code: 200,
    msg: "删除成功",
    data,
  };
});

// 重命名文件夹
newfile.post("/renameFolder", async (ctx) => {
  const params = ctx.request.body;
  const { id, folder_name } = params;
  let data = await article.renameFolder(id, folder_name);
  ctx.body = {
    code: 200,
    msg: "重命名成功",
    data,
  };
});

// 获取单个文件夹下的所有文件列表
newfile.post("/getFiles", async (ctx) => {
  const params = ctx.request.body;
  const { id } = params;
  let data = await article.getFolderFile(id);
  // 将时间戳转换为时间
  data.data.map((item) => {
    item.created_at = getCurrentTime(item.created_at);
  });
  // 过滤recycle为1的数据
  data.data = data.data.filter((item) => item.recycle === 0);

  ctx.body = {
    code: 200,
    msg: "获取成功",
    data,
  };
});

module.exports = newfile;
